<template>
  <information />

  <template v-if="store.basicData.status == 1">
    <requestion
      :dataImg="dataImg"
      v-model="desp"
      @uploadImg="uploadImg"
      @delImg="delImg"
    />
    <contact v-model:contactName="contactName" v-model:phone="phone" />
  </template>
  <status v-else />
  <div
    v-if="store.basicData.status == 1"
    class="btn-use"
    style="margin-bottom: 20px"
    @click="submit"
  >
    提交
  </div>
  <div class="btn-use" style="margin-bottom: 20px" @click="back">返回</div>
</template>
<script setup>
import { useRouter, useRoute } from "vue-router";
import { basicData } from "../store/data.js";
import status from "../components/status.vue";
import information from "../components/information.vue";
import requestion from "../components/requestion.vue";
import contact from "../components/contact.vue";
import { ref, getCurrentInstance, onBeforeMount } from "vue";

const store = basicData(); //pinia
const router = useRouter();
const route = useRoute();
const { proxy } = getCurrentInstance();
let dataImg = ref([]); //图片数组
let desp = ref(""); //问题描述
let phone = ref(null); //电话
let contactName = ref(""); //姓名
const clearFile = ref(null); //input  属性节点
onBeforeMount(() => {
  /* console.log(route.params.id, 199); */
  /* console.log(route.query.id, 199); */
});
//删除图片
const delImg = (i) => {
  dataImg.value.splice(i, 1);
  clearFile.value = null;
};
//上传图片
const uploadImg = (e) => {
  if (dataImg.value.length > 1) {
    alert("最多支持上传2张图片");
  } else {
    var e = window.event || e;
    // 获取图片地址
    var file = e.target.files[0];

    var formData = new FormData();

    formData.append("file", file);
    proxy.$axios
      .post(`${proxy.baseUrl}/common/upload`, formData)
      .then((res) => {
        dataImg.value.push(res.data.data.fullurl);
        clearFile.value = null;
      })
      .catch(() => {
        alert("图片上传失败");
      });
  }
};
//提交
const submit = () => {
  if (!/^1[3456789]\d{9}$/.test(phone.value)) {
    alert("手机号码有误，请重填");
  } else if (desp.value == "" || phone.value == "" || contactName.value == "") {
    alert("请输入完整信息");
  } else {
    proxy.$axios
      .post(`${proxy.baseUrl}/phase/fault`, {
        equipment_id: store.basicData.id, //设备id
        problem: desp.value, //问题描述
        contacts: contactName.value, //联系人
        contacts_mobile: phone.value, //联系电话
        images: dataImg.value.join(',') || '',
      })
      .then((res) => {
        alert(res.data.msg);
        if (res.data.msg == "成功") {
          getEquipmentInfo();
        }
      });
  }
};
/* 获取设备信息 */
const getEquipmentInfo = () => {
  proxy.$axios
    .post(`${proxy.baseUrl}/phase/getEquipment`, { id: store.basicData.id })
    .then((res) => {
      store.$patch((state) => {
        state.basicData = res.data.data;
        state.department_name = res.data.data.department.name;
      });
    });
};
//返回
const back = () => {
  router.go(-1);
};

//拍照上传图片
</script>
<style scoped>
</style>